/**
 * 
 */
package info.niwota.home.fm;

import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.speech.RecognizerIntent;
import android.text.format.DateFormat;

/**
 * @author qiangli
 *
 */
public final class Utils {

	/**
	 * 
	 */
	private Utils() {
	}

	
	public static boolean canSpeak(Context ctx) {
		PackageManager pm = ctx.getPackageManager();
		List<ResolveInfo> act = pm.queryIntentActivities(new Intent(
				RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
		return (act != null && act.size() > 0);
	}
	

	public static String sanitize(String name) {
		// replace space, ~, :,
		name = name.replaceAll("~", "_");
		name = name.replaceAll(" ", "_");
		name = name.replaceAll(":", "_");
		return name;
	}

	public static String createName() {
		long date = System.currentTimeMillis();
		return DateFormat.format("yyyy-MM-dd_kkmmss", date).toString();
	}

	public static String createName(String prefix, String ext) {
		long date = System.currentTimeMillis();
		return prefix + DateFormat.format("yyyy-MM-dd_kkmmss", date) + ext;
	}
	
	/**
	 * Parse uri into command and path
	 * 
	 * @param uri
	 * @return
	 */
	public static String[] parse(Uri uri) {
		String path = uri.getPath();
		String cmd = null;
		int pi = path.indexOf("!");
		if (pi > 0) {
			// this !/? conversion is to workaround the browser's failing to
			// pass query back
			// /bin/cmd!<uri>
			cmd = path.substring(0, pi);
			String q = path.substring(pi + 1);
			q = q.replace('!', '?');
			uri = Uri.parse(q);
			path = uri.getPath();
		}
		return new String[] { cmd, path, 
				uri.getQueryParameter("fileindex"),
				uri.getQueryParameter("maxbytes") };
	}

	/**
	 * Extract path part of cmd!path
	 * 
	 * @param uri
	 * @return
	 */
	public static String path(Uri uri) {
		String[] pa = parse(uri);
		return pa[1];
	}
}
